package com.dayuanit.dy14.atm.demo2.dy14atmweb.controller;

import com.dayuanit.dy14.atm.demo2.dy14atmcommon.dto.ResponseDTO;
import com.dayuanit.dy14.atm.demo2.dy14atmcommon.exception.BizException;
import com.dayuanit.dy14.atm.demo2.dy14atmdao.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public abstract class BaseController {
    protected static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Value("${md5.salt}")
    protected String md5Salt;

    @Autowired
    protected HttpSession session;

    @Autowired
    protected HttpServletRequest request;

    protected int getUserId() {
        Object object = session.getAttribute("loginUser");
        if (null == object) {
            throw new BizException("请重新登录");
        }

        if (object instanceof User) {
            User user = (User) object;
            return user.getId();
        }

        return 1;
    }

    @ExceptionHandler(BizException.class)
    public ResponseDTO processBizException(BizException be) {
        logger.error(be.getMessage(), be);
        return ResponseDTO.fail(be.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public ResponseDTO processException(Exception be) {
        //统一的校验信息处理
        if (be instanceof BindException) {
            BindException bindException = (BindException)be;
            return ResponseDTO.fail(bindException.getFieldError().getDefaultMessage());
        }
        logger.error(be.getMessage(), be);
        return ResponseDTO.fail("系统异常，请联系客服，电话：110");
    }
}
